package com.eshop.modules.category.rest;

import java.lang.invoke.SerializedLambda;
import com.eshop.modules.product.domain.StoreProduct;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import org.springframework.web.bind.annotation.DeleteMapping;
import java.io.Serializable;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.web.bind.annotation.PostMapping;
import com.eshop.modules.aop.ForbidSubmit;
import com.eshop.api.EshopException;
import cn.hutool.core.util.StrUtil;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.validation.annotation.Validated;
import com.eshop.modules.category.domain.StoreCategory;
import com.eshop.modules.category.service.dto.StoreCategoryDto;
import org.springframework.http.HttpStatus;
import java.util.List;
import org.springframework.http.ResponseEntity;
import org.springframework.data.domain.Pageable;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import io.swagger.annotations.ApiOperation;
import com.eshop.logging.aop.log.Log;
import java.io.IOException;
import com.eshop.modules.category.service.dto.StoreCategoryQueryCriteria;
import javax.servlet.http.HttpServletResponse;
import com.eshop.modules.product.service.StoreProductService;
import com.eshop.modules.category.service.StoreCategoryService;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import io.swagger.annotations.Api;

@Api(tags = { "商城:商品分类管理" })
@RestController
@RequestMapping({ "api" })
public class StoreCategoryController
{
    private final StoreCategoryService storeCategoryService;
    private final StoreProductService storeProductService;
    
    public StoreCategoryController(final StoreCategoryService storeCategoryService, final StoreProductService storeProductService) {
        this.storeCategoryService = storeCategoryService;
        this.storeProductService = storeProductService;
    }
    
    @Log("导出数据")
    @ApiOperation("导出数据")
    @GetMapping({ "/yxStoreCategory/download" })
    @PreAuthorize("@el.check('admin','YXSTORECATEGORY_SELECT')")
    public void download(final HttpServletResponse response, final StoreCategoryQueryCriteria criteria) throws IOException {
        this.storeCategoryService.download(this.storeCategoryService.queryAll(criteria), response);
    }
    
    @Log("查询商品分类")
    @ApiOperation("查询商品分类")
    @GetMapping({ "/yxStoreCategory" })
    @PreAuthorize("hasAnyRole('admin','YXSTORECATEGORY_ALL','YXSTORECATEGORY_SELECT')")
    public ResponseEntity getYxStoreCategorys(final StoreCategoryQueryCriteria criteria, final Pageable pageable) {
        final List<StoreCategoryDto> categoryDTOList = (List<StoreCategoryDto>)this.storeCategoryService.queryAll(criteria);
        return new ResponseEntity(this.storeCategoryService.buildTree((List)categoryDTOList), HttpStatus.OK);
    }
    
    @ForbidSubmit
    @Log("新增商品分类")
    @ApiOperation("新增商品分类")
    @PostMapping({ "/yxStoreCategory" })
    @CacheEvict(cacheNames = { "yshop:index_data" }, allEntries = true)
    @PreAuthorize("hasAnyRole('admin','YXSTORECATEGORY_ALL','YXSTORECATEGORY_CREATE')")
    public ResponseEntity create(@Validated @RequestBody final StoreCategory resources) {
        if (resources.getPid() != null && resources.getPid() > 0 && StrUtil.isBlank((CharSequence)resources.getPic())) {
            throw new EshopException("子分类图片必传");
        }
        final boolean checkResult = this.storeCategoryService.checkCategory((int)resources.getPid());
        if (!checkResult) {
            throw new EshopException("分类最多能添加2级哦");
        }
        return new ResponseEntity(this.storeCategoryService.save(resources), HttpStatus.CREATED);
    }
    
    @ForbidSubmit
    @Log("修改商品分类")
    @ApiOperation("修改商品分类")
    @CacheEvict(cacheNames = { "yshop:index_data" }, allEntries = true)
    @PutMapping({ "/yxStoreCategory" })
    @PreAuthorize("hasAnyRole('admin','YXSTORECATEGORY_ALL','YXSTORECATEGORY_EDIT')")
    public ResponseEntity update(@Validated @RequestBody final StoreCategory resources) {
        if (resources.getPid() != null && resources.getPid() > 0 && StrUtil.isBlank((CharSequence)resources.getPic())) {
            throw new EshopException("子分类图片必传");
        }
        if (resources.getId().equals(resources.getPid())) {
            throw new EshopException("自己不能选择自己哦");
        }
        final boolean checkResult = this.storeCategoryService.checkCategory((int)resources.getPid());
        if (!checkResult) {
            throw new EshopException("分类最多能添加2级哦");
        }
        this.storeCategoryService.saveOrUpdate(resources);
        return new ResponseEntity(HttpStatus.NO_CONTENT);
    }
    
    @ForbidSubmit
    @Log("删除商品分类")
    @ApiOperation("删除商品分类")
    @CacheEvict(cacheNames = { "yshop:index_data" }, allEntries = true)
    @DeleteMapping({ "/yxStoreCategory/{id}" })
    @PreAuthorize("hasAnyRole('admin','YXSTORECATEGORY_ALL','YXSTORECATEGORY_DELETE')")
    public ResponseEntity delete(@PathVariable final String id) {
        final String[] split;
        final String[] ids = split = id.split(",");
        for (final String newId : split) {
            this.delCheck(Integer.valueOf(newId));
            this.storeCategoryService.removeById((Serializable)Integer.valueOf(newId));
        }
        return new ResponseEntity(HttpStatus.OK);
    }
    
    private void delCheck(final Integer id) {
        final int count = ((LambdaQueryChainWrapper)this.storeCategoryService.lambdaQuery().eq(StoreCategory::getPid, id)).count();
        if (count > 0) {
            throw new EshopException("请先删除子分类");
        }
        final int countP = ((LambdaQueryChainWrapper)this.storeProductService.lambdaQuery().eq(StoreProduct::getCateId, id)).count();
        if (countP > 0) {
            throw new EshopException("当前分类下有商品不可删除");
        }
    }
}
